package com.whpost.service.wx.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.config.Wdpz;
import com.whpost.service.dao.t.TRegionDao;
import com.whpost.service.dao.t.TXzjgDao;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TRegion;
import com.whpost.service.entity.t.TXzjg;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.service.WxBaseServices;
import com.whpost.service.service.t.FileService;
import com.whpost.service.service.t.TApiNonceService;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import com.whpost.service.wx.dao.*;
import com.whpost.service.wx.entiy.*;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 *
 * @Author: Yin Zhuoyi
 * @Date: 2021/12/15 11:16
 */
@Service
public class WxXcServices extends BaseServices<WxXcMapper, WxXc> {

    @Resource
    private WxXxlyMapper wxXxlyMapper;
    @Resource
    private WxCyxxMapper wxCyxxMapper;
    @Resource
    private WxBslxMapper wxBslxMapper;
    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private TXzjgDao tXzjgDao;
    @Resource
    private TRegionDao tRegionDao;
    @Resource
    private WxBaomingCyxxMapper wxBaomingCyxxMapper;
    @Resource
    private WxBaomingTjMapper wxBaomingTjMapper;
    @Resource
    private Wdpz wdpz;
    @Resource
    private FileService fileService;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        try{
            JSONObject jsonObject = getData(map,loginId);
            if (StringUtils.isEmpty(loginId)){
                return new ResultInfo(500,"用户信息丢失！",null);
            }else{
                String curpage = "",pagesize="",cxmc="";
                QueryWrapper<WxXc> queryWrapper = new QueryWrapper<>();
                if (jsonObject.containsKey("curpage")) {
                    curpage = jsonObject.getString("curpage");
                }
                if (jsonObject.containsKey("pagesize")) {
                    pagesize = jsonObject.getString("pagesize");
                }
                if (jsonObject.containsKey("cxmc")) {
                    cxmc = jsonObject.getString("cxmc");
                }

                if (StringUtils.isEmpty(curpage)) curpage = "1";
                if (StringUtils.isEmpty(pagesize)) pagesize = "10";

                Page<WxXc> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

                ListInfo<WxXc> wxXcListInfo = new ListInfo<>();
                if (!StringUtils.isEmpty(cxmc))
                {
                    queryWrapper.like("fzmc",cxmc);
                }
                queryWrapper.eq("1","1");

                queryWrapper.orderByDesc("id");
                IPage<WxXc> wxXcIPage = getBaseMapper().selectPage(page,queryWrapper);

                PageInfo pageInfo = new PageInfo();
                pageInfo.setTotal(wxXcIPage.getTotal());
                pageInfo.setCurPage(wxXcIPage.getCurrent());
                pageInfo.setPageSize(wxXcIPage.getSize());
                pageInfo.setPageTotal(wxXcIPage.getPages());

                wxXcListInfo.setPageInfo(pageInfo);
                wxXcListInfo.setListInfo(wxXcIPage.getRecords());
                wxXcListInfo.setUserId(loginId);

                //查询条件的值
                Map<String,Object> cxtjMap = new HashMap<>();
                cxtjMap.put("cxmc",cxmc);

                //返回前端的内容
                Map<String,Object> rtnMap = new HashMap<>();
                rtnMap.put("cxjg",wxXcListInfo);
                rtnMap.put("cxtj",cxtjMap);

                ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
                return backRtn(resultInfo,loginId);
            }
        }catch (Exception e){
            e.printStackTrace();
            ResultInfo resultInfo = new ResultInfo(500, "成功返回！",null);
            return backRtn(resultInfo,loginId);
        }

    }

    //获取相册缩略图
    public byte[] getXcSlt(String id) {
        String wj = null;
        String basePath;

        // 确定基础路径
        String os = System.getProperty("os.name");
        if (os != null && os.contains("Windows")) {
            basePath = "d:\\wx\\xc\\";
        } else {
            basePath = "/home/wx/xc/";
        }

        try {
            // 尝试从数据库获取文件名
            WxXc wxXc = getBaseMapper().selectById(id);
            if (wxXc != null) {
                wj = wxXc.getSlt();
            }
        } catch (Exception e) {
            // 发生任何异常都忽略，使用默认文件
            // 可以添加日志记录: log.warn("获取数据库记录异常，将使用默认文件", e);
        }

        // 尝试读取文件（先尝试原始文件，失败则用默认文件）
        return readFile(basePath, wj);
    }


    //获取相册原图
    public byte[] getXcYt(String id) {
        String wj = null;
        String basePath;

        // 确定基础路径
        String os = System.getProperty("os.name");
        if (os != null && os.contains("Windows")) {
            basePath = "d:\\wx\\xc\\";
        } else {
            basePath = "/home/wx/xc/";
        }

        try {
            // 尝试从数据库获取文件名
            WxXc wxXc = getBaseMapper().selectById(id);
            if (wxXc != null) {
                wj = wxXc.getYt();
            }
        } catch (Exception e) {
            // 发生任何异常都忽略，使用默认文件
            // 可以添加日志记录: log.warn("获取数据库记录异常，将使用默认文件", e);
        }

        // 尝试读取文件（先尝试原始文件，失败则用默认文件）
        return readFile(basePath, wj);
    }

    // 抽取文件读取逻辑为单独方法
    private byte[] readFile(String basePath, String fileName) {
        // 如果原始文件名不存在或无效，直接使用默认文件
        if (fileName == null || fileName.trim().isEmpty()) {
            fileName = "mrfm.png";
        }

        File file = new File(basePath + fileName);
        // 如果文件不存在，尝试默认文件
        if (!file.exists() || !file.isFile()) {
            fileName = "mrfm.png";
            file = new File(basePath + fileName);
            // 如果默认文件也不存在，返回null
            if (!file.exists() || !file.isFile()) {
                return null;
            }
        }

        // 读取文件内容
        try (FileInputStream inputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            int bytesRead = inputStream.read(bytes);
            if (bytesRead == file.length()) {
                return bytes;
            }
        } catch (Exception e) {
            // 读取文件发生异常，返回null
            // 可以添加日志记录: log.error("读取文件异常", e);
        }

        return null;
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, List<MultipartFile> file, String data) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            JSONObject jsonObject = getDataStr(data,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",fzmc="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("fzmc")) {
                fzmc = jsonObject.getString("fzmc");
            }

            if (StringUtils.isEmpty(fzmc)) fzmc="默认分组";

            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"stampmb.save");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);

            String os = System.getProperty("os.name");
            String picPathReal = "";
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                picPathReal = "d:\\wx\\xc\\";
            } else {
                //linux
                picPathReal = "/home/wx/xc/";
            }
            WxXc wxXc = new WxXc();

            if (null!=file){
                for (MultipartFile wj : file) {
                    if (StringUtils.isEmpty(wj.getOriginalFilename())){
                        continue;
                    }
                    //保存模版
                    wxXc = new WxXc();
                    wxXc.setFzmc(fzmc);
                    getBaseMapper().insert(wxXc);



                    String wjm = String.valueOf(wxXc.getId()) + ".jpg";
                    String wjm_slt = String.valueOf(wxXc.getId()) + "_slt.jpg";
                    wxXc.setSlt(wjm_slt);
                    wxXc.setYt(wjm);

                    getBaseMapper().updateById(wxXc);

                    fileService.uploadFileSlt(wj, picPathReal, wjm,wjm_slt);
                }
                return new ResultInfo(0,"操作成功！",null);
            }else{
                return new ResultInfo(500,"没有任何图片上传！",null);
            }



        }
    }

}
